<template>
  <div class="app-container">
    <div class="page-card top-tabs">
      <el-tabs v-model="queryParams.examSubjectId" @tab-click="changeTab">
        <el-tab-pane
          v-for="item in tabList"
          :key="item.id"
          :label="item.name"
          :name="item.id.toString()"
        ></el-tab-pane>
      </el-tabs>
    </div>
    <div class="page-card m-top">
      <div class="page-form">
        <el-select
          v-hasRole="['admin']"
          v-model="queryParams.examSchoolId"
          placeholder="全部学校"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in xxlb"
            :key="dict.id"
            :label="dict.schoolName"
            :value="dict.id"
          />
        </el-select>
        <el-input
          v-model="queryParams.admissionNo"
          placeholder="准考证号"
          clearable
          @input="handleSearch"
        />
        <el-input
          v-model="queryParams.studentName"
          placeholder="姓名"
          clearable
          @input="handleSearch"
        />
        <!-- <el-button
          @click="calculateEndowScore"
          type="primary"
          style="height: 36px"
          >赋分</el-button
        > -->
        <el-button
          :loading="loadingScoreStatistics"
          @click="scoreStatisticsBtn"
          type="primary"
          style="height: 36px"
          v-if="queryParams.examSubjectId == -1"
          >计算成绩分段统计</el-button
        >

        <el-button
          :loading="loadingQuestionAnalysis"
          @click="questionAnalysisBtn"
          type="primary"
          style="height: 36px"
          v-if="queryParams.examSubjectId == -1"
          >题目分析</el-button
        >
      </div>
      <!-- 总分表格 -->
      <el-table
        stripe
        border
        v-loading="loading"
        :data="tableDataAll"
        style="width: 100%; margin-top: 20px"
        row-key="admissionNo"
        v-if="queryParams.examSubjectId == -1"
      >
        <el-table-column
          label="准考证号"
          align="center"
          prop="admissionNo"
          :show-overflow-tooltip="true"
          width="120"
        />
        <el-table-column
          label="姓名"
          align="center"
          prop="studentName"
          width="140"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="学校"
          align="center"
          prop="schoolName"
          width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="班级"
          align="center"
          prop="className"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-for="value in tableHeader"
          :key="value"
          :label="value"
          align="center"
          :prop="value"
          :show-overflow-tooltip="true"
        />
        <!-- <el-table-column v-for="item in questionList" :key="item.questionId"
          :label="item.questionName + item.questionNumber" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span :class="{
              disciplinary:
                scope.row.examScoreManageQuestion[item.questionId] &&
                scope.row.examScoreManageQuestion[item.questionId]
                  .disciplinary == 1,
            }">
              {{
                scope.row.examScoreManageQuestion[item.questionId] &&
                scope.row.examScoreManageQuestion[item.questionId].value
              }}
            </span>
          </template>
        </el-table-column> -->
      </el-table>
      <!-- 各学科表格 -->
      <el-table
        stripe
        border
        ref="tableList"
        v-loading="loading"
        :data="tableData"
        style="width: 100%; margin-top: 20px"
        row-key="id"
        v-if="queryParams.examSubjectId != -1"
        @sort-change="handleSortChange"
      >
        <el-table-column
          label="准考证号"
          align="center"
          prop="admissionNo"
          :show-overflow-tooltip="true"
          width="120"
        />
        <el-table-column
          label="姓名"
          align="center"
          prop="studentName"
          width="140"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="学校"
          align="center"
          prop="schoolName"
          width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="班级"
          align="center"
          prop="className"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="总分"
          align="center"
          prop="totalScore"
          sortable="custom"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="客观题"
          align="center"
          prop="objectiveScore"
          :show-overflow-tooltip="true"
          sortable="custom"
          width="110"
        />
        <el-table-column
          label="主观题"
          align="center"
          prop="subjectiveScore"
          :show-overflow-tooltip="true"
          sortable="custom"
          width="110"
        />
        <el-table-column
          v-for="item in questionList"
          :key="item.questionId"
          :label="item.questionName + item.questionNumber"
          align="center"
          :show-overflow-tooltip="true"
          sortable="custom"
          width="130"
        >
          <template slot-scope="scope">
            <span
              :class="{
                disciplinary:
                  scope.row.examScoreManageQuestion[item.questionId] &&
                  scope.row.examScoreManageQuestion[item.questionId]
                    .disciplinary == 1,
              }"
            >
              {{
                scope.row.examScoreManageQuestion[item.questionId] &&
                scope.row.examScoreManageQuestion[item.questionId].value
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="300"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="cxbd(scope.row)">重新比对</el-link>
            <el-link
              type="primary"
              v-if="scope.row.frontImgPath && scope.row.backImgPath"
              @click="dtk(scope.row)"
              >答题卡</el-link
            >
            <template v-if="scope.row.publishStatus != 1">
              <el-link
                v-if="showXgfs(scope.row)"
                v-hasRole="['admin']"
                type="primary"
                @click="xgfs(scope.row)"
                >修改分数</el-link
              >
              <el-link
                v-hasRole="['admin']"
                type="primary"
                @click="edit(scope.row)"
                >调整分数</el-link
              >
              <el-link
                v-hasRole="['admin']"
                type="danger"
                v-if="
                  scope.row.examScoreManageQuestionVos &&
                  scope.row.examScoreManageQuestionVos[0] &&
                  scope.row.examScoreManageQuestionVos[0].disciplinary == 0
                "
                @click="wj(scope.row, 1)"
                >违纪</el-link
              >
              <el-link
                v-hasRole="['admin']"
                type="danger"
                v-if="
                  scope.row.examScoreManageQuestionVos &&
                  scope.row.examScoreManageQuestionVos[0] &&
                  scope.row.examScoreManageQuestionVos[0].disciplinary == 1
                "
                @click="wj(scope.row, 0)"
                >取消违纪</el-link
              >
            </template>
          </template></el-table-column
        >
      </el-table>
    </div>
    <el-dialog
      title="客观题重新比对（仅单选）"
      :visible.sync="cxbdDialogVisible"
      width="600px"
      :before-close="cxbdHandleClose"
    >
      <div style="display: flex">
        <p style="margin-right: 30px">准考证号：{{ rowData.admissionNo }}</p>
        <p style="margin-right: 30px">考生姓名：{{ rowData.studentName }}</p>
        <p>考生班级：{{ rowData.className }}</p>
      </div>
      <div style="margin-top: 10px">
        <el-radio-group v-model="cxbdForm.questionId">
          <el-radio
            v-for="(value, index) in questionList.filter(
              (item) => item.questionTypeId == 31
            )"
            :key="index"
            :label="value.questionId"
            style="width: 18%; margin-bottom: 10px"
          >
            {{ value.questionName }}-{{ value.questionNumber }}
          </el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cxbdHandleClose">取 消</el-button>
        <el-button type="primary" @click="cxbdSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <div class="page-bottom">
      <div class="sel-box">
        <p>共 {{ total }} 项</p>
        <el-dropdown
          @command="handleCommand"
          v-if="
            (dcStatus == 2 || (dcStatus == 0 && total != 0)) &&
            queryParams.examSubjectId != -1
          "
          trigger="hover"
          ref="dropdown"
          @click.native="toggleDropdown"
        >
          <span class="el-dropdown-link">
            {{ eldropName }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="下载成绩">下载成绩</el-dropdown-item>
            <el-dropdown-item command="重新生成">重新生成</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button
          type="primary"
          @click="downloadAllScore"
          :loading="loadingDownloadAllScore"
          v-if="queryParams.examSubjectId == -1"
          >下载成绩</el-button
        >

        <!--  -->
        <!-- <el-button
          v-else
          :type="dcStatus == '0' ? 'success' : 'primary'"
          :loading="dcStatus == 1"
          :disabled="total == 0"
          >{{
            dcStatus == "0"
              ? "生成导出成绩"
              : dcStatus == "0"
              ? "生成中"
              : "导出成绩"
          }}</el-button> -->
        <el-button
          type="primary"
          @click="upload.open = true"
          v-hasRole="['admin']"
          v-if="queryParams.examSubjectId == -1"
          >导入总成绩</el-button
        >
        <!-- <el-button type="primary" @click="cjfx" v-hasRole="['admin']"
          >教师端</el-button
        >
        <el-button type="primary" @click="yyd" v-hasRole="['admin']"
          >运营端</el-button
        > -->
        <el-button
          :loading="loadingTotalScore"
          @click="totalScoreBtn"
          type="primary"
          style="height: 36px"
          v-if="queryParams.examSubjectId == -1"
          >计算总分</el-button
        >
        <template
          v-if="
            tableData.length > 0 &&
            tableData[0].publishStatus != 1 &&
            queryParams.examSubjectId != -1
          "
        >
          <el-button type="primary" @click="blfsShow" v-hasRole="['admin']"
            >补录分数</el-button
          >
          <el-button type="primary" @click="edit(false)" v-hasRole="['admin']"
            >批量调整</el-button
          >
        </template>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="handleSearch"
      />
    </div>

    <!--补录分数 -->
    <el-dialog
      ref="blfsDialog"
      class="editKmVisible"
      title="补录分数"
      :visible.sync="blfsVisible"
      width="436px"
      :before-close="beforeClose"
    >
      <el-form
        ref="blfsForm"
        :model="blfsForm"
        :rules="blfsRules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="学校名称" prop="schoolId">
          <el-select v-model="blfsForm.schoolId" filterable>
            <el-option
              v-for="dict in xxlb"
              :key="dict.id"
              :label="dict.schoolName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="准考证号" prop="admissionNo">
          <el-input
            v-model="blfsForm.admissionNo"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="blfsForm.studentNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input
            v-model="blfsForm.studentName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="学生班级" prop="classId">
          <el-select v-model="blfsForm.classId">
            <el-option
              v-for="dict in bjlb"
              :key="dict.id"
              :label="dict.className"
              :value="dict.id.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-for="item in blfsForm.questionList"
          :key="item.questionId"
          :label="item.questionName + item.questionNumber"
        >
          <el-input v-model="item.score"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" :loading="loading" @click="blfsSubmit"
          >保 存</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改分数 -->
    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      :title="(editForm.row ? '单个' : '批量') + '修改小题分数'"
      :visible.sync="editKmVisible"
      width="1000px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="auto"
      >
        <div class="edit-info" v-if="editForm.row">
          <p>
            准考证号：<span>{{ editForm.row.admissionNo }} </span>
          </p>
          <p>
            考生姓名：<span>{{ editForm.row.studentName }}</span>
          </p>
          <p>
            考生班级：<span>{{ editForm.row.className }}</span>
          </p>
        </div>

        <div v-else>
          <div>
            <el-radio v-model="editType" label="1">指定范围修改</el-radio>
            <el-radio v-model="editType" label="2">固定范围修改</el-radio>
          </div>
          <div style="margin-top: 20px">
            <el-form-item
              label="准考证号"
              prop="admissionNos"
              label-width="80px"
              v-if="editType == '1'"
            >
              <el-input
                type="textarea"
                v-model="editForm.admissionNos"
                placeholder="输入多个准考证号以英文,分隔"
              ></el-input>
            </el-form-item>
            <template v-if="editType == '2'">
              <el-form-item label="修改范围" label-width="80px">
                <el-select v-model="editRange">
                  <el-option label="校级" value="1"></el-option>
                  <el-option label="班级" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="修改学校"
                label-width="80px"
                v-if="editRange == 1"
                prop="schoolId"
              >
                <el-select v-model="editForm.schoolId" multiple>
                  <el-option
                    v-for="dict in xxlb"
                    :key="dict.id"
                    :label="dict.schoolName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item
                label="选择学校"
                label-width="80px"
                v-if="editRange == 2"
              >
                <el-select v-model="schoolId">
                  <el-option
                    v-for="dict in xxlb"
                    :key="dict.id"
                    :label="dict.schoolName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="选择班级"
                label-width="80px"
                v-if="editRange == 2"
                prop="classId"
              >
                <el-select v-model="editForm.classId" multiple>
                  <el-option
                    v-for="dict in editBjlb"
                    :key="dict.id"
                    :label="dict.className"
                    :value="dict.id.toString()"
                  />
                </el-select>
              </el-form-item>
            </template>
          </div>
        </div>

        <el-divider></el-divider>
        <el-checkbox
          v-model="checkAll"
          @change="handleCheckAllChange"
          :indeterminate="allIndeterminate"
          >全选</el-checkbox
        >
        <div
          class="check-row"
          v-for="(item, index) in checkData"
          :key="'checkrow_' + index"
        >
          <div style="margin-bottom: 15px">
            <el-checkbox
              :indeterminate="checkRows[index].indeterminate"
              v-model="checkRows[index].value"
              @change="handleCheckRowChange(checkRows[index].value, index)"
            >
              整行
            </el-checkbox>
          </div>
          <el-checkbox-group
            v-model="item.value"
            @change="handleCheckChange(index)"
          >
            <el-checkbox
              v-for="v in item.item"
              :label="v.questionId"
              :key="v.questionId"
              ><span style="font-weight: bold">{{
                v.questionName + v.questionNumber
              }}</span></el-checkbox
            >
          </el-checkbox-group>
        </div>
        <el-divider></el-divider>
        <el-row style="margin-top: 20px">
          <el-col :span="9">
            <el-form-item label="操作得分" prop="score" label-width="80px">
              <el-input
                v-model="editForm.score"
                placeholder="请填写符号加数字"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计算方式" prop="roundOff">
              <el-select v-model="editForm.roundOff">
                <el-option label="使用尾数1/0.5" value="1"></el-option>
                <el-option label="使用四舍五入" value="2"></el-option>
                <el-option label="默认" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" :loading="loading" @click="editSubmit(false)"
          >保 存</el-button
        >
        <el-button type="primary" :loading="loading" @click="editSubmit(true)"
          >保存并继续</el-button
        >
      </div>
    </el-dialog>
    <!-- 导入总成绩-弹框 -->
    <el-dialog
      title="导入总成绩"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      width="400px"
      append-to-body
    >
      <span style="color: #d54941"
        >注意：重复导入时，原有数据将被新导入数据覆盖</span
      >
      <div style="margin: 20px 0">
        <span style="margin-right: 10px">导入学校</span>
        <el-select
          v-model="upload.deptId"
          placeholder="请选择"
          @change="getExamSchoolId"
        >
          <el-option
            v-for="dict in xxlb"
            :key="dict.schoolId"
            :label="dict.schoolName"
            :value="dict.schoolId"
          />
        </el-select>
      </div>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        action=""
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :http-request="customUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-image-viewer
      v-if="imgViewerVisible"
      :on-close="closeImgViewer"
      :url-list="imgList"
    />
  </div>
</template>

<script>
import { debounce } from "lodash";
import { scanExamSubject } from "@/api/xmgl/smgl";
import { saveAs } from "file-saver";
import { scanQuestionCardSchoolListSchool } from "@/api/xmgl/tkcx";
import {
  systemScoreManageList,
  systemScoreManageQuestionName,
  systemScoreManageDisciplinary,
  systemScoreManageAdjustmentScore,
  systemScoreManageAdditionScore,
  systemScoreManageExportStatus,
  systemScoreManageExport,
  systemScoreManageCxsc,
  getTotalScoreList,
  importTotalScore,
  getStudentTotalScoreInfo,
  calculateEndowScore,
  // 计算成绩分段统计
  calculateScoreStatistics,
  // 计算总分
  calculateTotalScore,
  // 题目分析
  questionAnalysis,
  // 下载总成绩
  downloadAllScore,
} from "@/api/xmgl/cjgl";
import { classlist } from "@/api/xmgl/xsgl";
import { getToken } from "@/utils/auth";
export default {
  name: "Project_cjgl",
  components: {
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer"),
  },
  data() {
    return {
      loadingDownloadAllScore: false,
      importSchoolId: null,

      importSchoolList: [],

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        deptId: "",
        examSchoolId: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/exam/school/import",
      },

      cxbdDialogVisible: false,
      rowData: {},
      cxbdForm: {
        questionId: null,
      },

      firstLoad: true,

      loading: false,
      xmxx: {},
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        examSubjectId: "",
      },
      activeName: "",

      tabList: [],

      tableData: [],
      total: 0,
      questionList: [],

      xxlb: [],
      qbbjlb: [],

      blfsVisible: false,
      blfsForm: {
        admissionNo: "",
        studentName: "",
        schoolId: "",
        classId: "",
        studentNo: "",
      },
      blfsRules: {
        admissionNo: [
          { required: true, message: "准考证号不能为空", trigger: "blur" },
        ],
        studentName: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" },
        ],
        schoolId: [
          { required: true, message: "学校名称不能为空", trigger: "change" },
        ],
        classId: [
          { required: true, message: "学生班级不能为空", trigger: "change" },
        ],
        studentNo: [
          { required: true, message: "学号不能为空", trigger: "change" },
        ],
      },

      editKmVisible: false,
      editForm: {
        row: null,
        score: "",
        roundOff: "1",
        admissionNos: "",
        schoolId: [],
        classId: [],
      },
      checkData: [],
      checkAll: false,
      checkRows: [],
      allIndeterminate: false,
      rules: {
        score: [
          { required: true, message: "操作得分不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              let reg = /^[\+\-\*][0-9]+(\.[0-9]+)?$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("格式错误，例：*1.2"));
              }
            },
            trigger: "blur",
          },
        ],

        admissionNos: [
          {
            required: true,
            message: "准考证号不能为空",
            trigger: "blur",
          },
        ],
        schoolId: [
          {
            required: true,
            message: "修改学校不能为空",
            trigger: "change",
          },
        ],
        classId: [
          {
            required: true,
            message: "修改班级不能为空",
            trigger: "change",
          },
        ],
      },
      editType: "1",
      editRange: "1",
      schoolId: "",

      imgViewerVisible: false,
      imgList: [],

      dcStatus: 0,
      type: 1,
      eldropName: "导出成绩",
      tableHeader: [
        "总分",
        "语文",
        "数学",
        "英语",
        "物理",
        "化学",
        "生物",
        "政治",
        "历史",
        "地理",
        "日语",
      ],

      tableDataAll: [],
      // 计算成绩分段统计loading
      loadingScoreStatistics: false,
      // 计算总分loading
      loadingTotalScore: false,
      // 题目分析loading
      loadingQuestionAnalysis: false,
    };
  },
  computed: {
    bjlb: function () {
      return this.qbbjlb.filter((item) => {
        return item.schoolId == this.blfsForm.schoolId;
      });
    },

    editBjlb: function () {
      return this.qbbjlb.filter((item) => {
        return item.schoolId == this.schoolId;
      });
    },
  },
  created() {
    this.loading = true;
    this.$store.dispatch("getXmxx").then((res) => {
      this.xmxx = res;

      scanExamSubject({ examId: this.xmxx.id }).then((res) => {
        console.log(res.data, "wxd");

        this.tabList = [{ name: "总分", id: "-1" }, ...res.data];
        if (this.$route.query.examSubjectId) {
          this.queryParams.examSubjectId = this.$route.query.examSubjectId;
        } else {
          this.queryParams.examSubjectId = res.data[0].id.toString();
        }
        scanQuestionCardSchoolListSchool({ examId: this.xmxx.id }).then(
          (res) => {
            this.xxlb = res.rows;

            if (!this.$auth.hasRole("admin")) {
              this.queryParams.examSchoolId = this.xxlb.filter((item) => {
                return this.$store.state.user.deptId == item.schoolId;
              })[0].id;
            }
            if (this.queryParams.examSubjectId == -1) {
              // 总分
              this.getTotalScore();
            } else {
              this.getList();
            }
          }
        );
      });

      classlist({
        pageNum: 1,
        pageSize: 9999,
        examId: this.xmxx.id,
      }).then((res) => {
        this.qbbjlb = res.rows;
      });
    });
  },

  activated() {
    if (!this.firstLoad) {
      if (this.$store.state.app.isRefresh) {
        this.queryParams.examSubjectId = this.$route.query.examSubjectId;
        this.queryParams.pageNum = 1;
        this.$nextTick(() => {
          if (this.queryParams.examSubjectId == -1) {
            // 总分
            this.getTotalScore();
          } else {
            this.getList();
          }
        });
      } else {
        if (this.queryParams.examSubjectId == -1) {
          // 总分
          this.getTotalScore();
        } else {
          this.getList();
        }
      }
    }
    this.firstLoad = false;
    this.$store.dispatch("app/setIsRefresh", false);
  },
  methods: {
    // 数据排序
    handleSortChange(sortObj) {
      let item = this.questionList.find((item) => {
        return sortObj.column.label == item.questionName + item.questionNumber;
      });
      if(item){
        this.queryParams.questionId = item.questionId
      }
      // console.info(item)
      // return false
      if(sortObj.order==='ascending'){
        this.queryParams.sortType = 2
      }else{
        this.queryParams.sortType = 1
      }
      if(sortObj.column.label=='总分'){
        this.queryParams.scoreSortType = 1
      }else if(sortObj.column.label=='客观题'){
        this.queryParams.scoreSortType = 2
      }else if(sortObj.column.label=='主观题'){
        this.queryParams.scoreSortType = 3
      }else if(sortObj.column.label.indexOf('单选题')!=-1){
        this.queryParams.scoreSortType = 4
      }else if(item&&item.groupQuestion!=1){
        this.queryParams.scoreSortType = 5
      }else{
        this.queryParams.scoreSortType = 6
      }
      // console.info( this.queryParams);
      this.getList()
    },
    calculateEndowScore() {
      let subjectName = this.tabList.filter((item) => {
        return item.id == this.queryParams.examSubjectId;
      })[0].name;

      this.$confirm(`(开发者模式)确认为本次考试赋分吗？`, "学科赋分", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        calculateEndowScore({
          examId: this.xmxx.id,
        }).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "赋分成功",
            });
            this.getList();
          }
        });
      });
    },
    // 计算成绩分段统计
    scoreStatisticsBtn() {
      this.$confirm(`(开发者模式)确认进行成绩分段统计吗？`, "成绩分段统计", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loadingScoreStatistics = true;
        calculateScoreStatistics({
          examId: this.xmxx.id,
        })
          .then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "成绩分段统计成功",
              });
            }
          })
          .finally(() => {
            this.loadingScoreStatistics = false;
          });
      });
    },
    // 总成绩
    totalScoreBtn() {
      this.$confirm(`确认计算总分吗？`, "总成绩计算", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loadingTotalScore = true;
        calculateTotalScore({
          examId: this.xmxx.id,
        })
          .then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "总成绩计算成功",
              });
            }
          })
          .finally(() => {
            this.loadingTotalScore = false;
          });
      });
    },
    // 问题分析
    questionAnalysisBtn() {
      this.$confirm(`(开发者模式)确认进行题目分析吗？`, "题目分析", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loadingQuestionAnalysis = true;
        questionAnalysis({
          examId: this.xmxx.id,
        })
          .then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "题目分析成功",
              });
            }
          })
          .finally(() => {
            this.loadingQuestionAnalysis = false;
          });
      });
    },
    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),
    handleSearch() {
      if (this.queryParams.examSubjectId == -1) {
        // 总分
        this.getTotalScore();
      } else {
        this.getList();
      }
    },
    getTotalScore() {
      this.loading = true;
      // 1：总分 2：客观题总分 3：主观题总分  4：单科分(客观题) 5：单科分(主观题 非题组) 6：单科分(主观题 题组) 
      getStudentTotalScoreInfo({
        examId: this.xmxx.id,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        studentName: this.queryParams.studentName,
        admissionNo: this.queryParams.admissionNo,
        schoolId: this.queryParams.examSchoolId,
        scoreSortType:this.queryParams.scoreSortType,
        sortTyp:this.queryParams.sortTyp,
        questionId:this.queryParams.questionId
      })
        .then((res) => {
          if (res.code == 200) {
            this.total = res.total;

            let data =
              res.rows.map((item) => {
                let obj = {};
                item.forEach((item2) => {
                  obj[item2.examSubjectName] = item2.totalScore;
                });
                obj.admissionNo = item[0].admissionNo || "";
                obj.studentName = item[0].studentName || "";
                obj.schoolName = item[0].schoolName || "";
                obj.className = item[0].className || "";
                console.log(obj, "obj");

                return obj;
              }) || [];
            console.log(data, "全部输");

            this.tableDataAll = data;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    changeTab(tab) {
      console.log(this.queryParams.examSubjectId);
      this.queryParams.pageNum = 1;
      // this.tableData = []
      // this.tableDataAll = []
      this.$nextTick(() => {
        if (this.queryParams.examSubjectId == -1) {
          // 总分
          this.getTotalScore();
        } else {
          this.getList();
        }
      });
    },
    getExamSchoolId(value) {
      this.upload.examSchoolId = this.xxlb.filter((item) => {
        return item.schoolId == value;
      })[0].id;
    },
    customUpload(option) {
      let data = {
        file: option.file,
      };
      this.upload.isUploading = true;
      importTotalScore(
        data,
        this.upload.deptId,
        this.xmxx.id,
        this.upload.examSchoolId
      )
        .then((res) => {
          console.info(res, "resssss");
          if (res && res.data && res.data.size != 0) {
            // 直接使用response.data（已为blob类型）
            const blob = new Blob([res.data]);
            // 获取文件名
            const filename = "总成绩导入结果.xlsx";
            saveAs(blob, filename);
            this.upload.open = false;
            this.upload.deptId = "";
            this.upload.examSchoolId = "";

            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.handleSearch();
            this.$alert(
              "失败原因及原始表格已下载，请修改后再重新导入",
              "导入失败!",
              {
                confirmButtonText: "确定",
                customClass: "my-alert",
                callback: (action) => {},
              }
            );
          } else {
            this.upload.open = false;
            this.upload.deptId = "";
            this.upload.isUploading = false;
            this.upload.examSchoolId = "";
            this.$refs.upload.clearFiles();
            this.$message({
              message: "导入成功！",
              duration: 3000,
              type: "success",
            });
            this.handleSearch();
          }
        })
        .finally(() => {
          this.upload.isUploading = false;
        });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.deptId = "";
      this.upload.examSchoolId = "";
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        "https://bs-exam-bucket.oss-cn-beijing.aliyuncs.com/dev/bsta/exam/uploadPath/upload/template/grade_summary.xlsx"
      );
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.deptId) {
        this.$message.error("请选择部门");
        return;
      }
      this.$refs.upload.submit();
    },
    cxbdSubmit() {
      if (!this.cxbdForm.questionId) {
        this.$message.error("请选择客观题");
        return;
      }
      let data = {
        examSubjecId: this.queryParams.examSubjectId,
        studentId: this.rowData.studentId,
        questionId: this.cxbdForm.questionId,
      };
      systemScoreManageCxsc(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("比对成功");
          this.cxbdDialogVisible = false;
          this.getList();
        }
      });
    },
    cxbdHandleClose() {
      this.cxbdDialogVisible = false;
      this.cxbdForm.questionId = null;
      this.rowData = {};
    },
    getList() {
      if (this.timer) {
        this.endTime();
      }
      this.loading = true;
      this.getStatus();
      this.tableData = [];
      systemScoreManageList({ ...this.queryParams, examId: this.xmxx.id }).then(
        (response) => {
          response.rows.map((item) => {
            item.examScoreManageQuestion = {};
            if (item.examScoreManageQuestionVos) {
              item.examScoreManageQuestionVos.map((v) => {
                item.examScoreManageQuestion[v.questionId] = {
                  value: v.score,
                  disciplinary: v.disciplinary,
                };
              });
            }
          });
          this.tableData = response.rows;
          this.total = response.total;

          systemScoreManageQuestionName({
            examSubjectId: this.queryParams.examSubjectId,
          })
            .then((res) => {
              this.questionList = res.data;
            })
            .finally(() => {
              this.loading = false;
            });
        }
      );
    },
    beforeClose(done) {
      let formName;
      if (this.blfsVisible) {
        formName = "blfsForm";
        this.blfsForm = {
          admissionNo: "",
          studentName: "",
          schoolId: "",
          studentNo: "",
          classId: "0",
        };
      } else if (this.editKmVisible) {
        formName = "editForm";
        this.editForm = {
          row: null,
          score: "",
          roundOff: "1",
          admissionNos: "",
          schoolId: [],
          classId: [],
        };

        this.schoolId = "";
      }
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
        this.blfsVisible = false;
      });
    },
    cxbd(row) {
      this.cxbdDialogVisible = true;
      this.rowData = row;
    },

    wj(row, disciplinary) {
      let examSubjectName = this.tabList.filter((item) => {
        return this.queryParams.examSubjectId == item.id;
      })[0].name;

      let modal = {
        title: disciplinary === 1 ? "违纪处理" : "取消违纪",
        msg:
          disciplinary === 1
            ? `确定后该名学生 ${examSubjectName} 考试成绩总分/小题分归零`
            : "是否取消改名学生违纪操作",
      };

      this.$modal.confirm(modal.msg, modal.title).then(() => {
        let zgt = {
          scoreType: "1",
          ids: [],
        };

        let kgt = {
          scoreType: "0",
          ids: [],
        };

        row.examScoreManageQuestionVos.map((item) => {
          if (item.scoreType === 0) {
            kgt.ids.push(item.id);
          } else if (item.scoreType === 1) {
            zgt.ids.push(item.id);
          }
        });

        let data = [];
        if (zgt.ids.length > 0) {
          data.push(zgt);
        }
        if (kgt.ids.length > 0) {
          data.push(kgt);
        }
        systemScoreManageDisciplinary({
          disciplinary: disciplinary,
          examScoreQuestions: data,
          examId: this.xmxx.id,
          examSubjectId: this.queryParams.examSubjectId,
        }).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.$refs.tableList.clearSelection();
          this.ids = [];
          this.getList();
        });
      });
    },
    getStatus() {
      systemScoreManageExportStatus({
        examId: this.xmxx.id,
        examSubjectId: this.queryParams.examSubjectId,
      }).then((res) => {
        this.dcStatus = res.data.status;
        if (res.data.status == "1" && !this.timer) {
          this.startTime();
        } else if (res.data.status == "2" && this.timer) {
          this.eldropName = "导出成绩";
          this.endTime();
        }
      });
    },
    downloadAllScore() {
      this.loadingDownloadAllScore = true;
      downloadAllScore({
        examId: this.xmxx.id,
        // examSubjectId: this.queryParams.examSubjectId,
      })
        .then((res) => {
          try {
            // 创建一个a标签用于下载
            const link = document.createElement("a");
            // 创建下载的URL对象
            const url = window.URL.createObjectURL(res.data);
            // 设置a标签属性
            link.href = url;
            // 从响应头中获取文件名（如果后端提供）
            const contentDisposition = res.headers?.["content-disposition"];
            let fileName = `总成绩_student_scores_${new Date().getTime()}.xlsx`; // 默认文件名
            if (contentDisposition) {
              const matches = contentDisposition.match(/filename=([^;]+)/);
              if (matches && matches[1]) {
                fileName = decodeURIComponent(matches[1].replace(/"/g, ""));
              }
            }
            link.download = fileName;
            // 触发下载
            document.body.appendChild(link);
            link.click();
            // 清理
            setTimeout(() => {
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
            }, 100);
            this.loadingDownloadAllScore = false;
          } catch (error) {
            this.$message.error("下载失败，请重试");
            this.loadingDownloadAllScore = false;
          }
        })
        .catch(() => {
          this.loadingDownloadAllScore = false;
        });
    },
    //导出成绩下拉
    handleCommand(data) {
      this.eldropName = data;
      if (data == "下载成绩") {
        this.dcStatus = "2";
        this.type = 1;
      } else {
        this.dcStatus = "1";
        this.type = 2;
      }
      this.dc();
    },
    toggleDropdown() {
      const drop = this.$refs.dropdown;
      drop.visible ? drop.hide() : drop.show();
    },
    startTime() {
      this.timer = setInterval(() => {
        this.getStatus();
      }, 5000);
    },
    endTime() {
      clearInterval(this.timer);
      this.timer = null;
    },
    dc() {
      if (this.dcStatus == "0") {
        this.dcStatus = "1";
      }
      systemScoreManageExport({
        examId: this.xmxx.id,
        examSubjectId: this.queryParams.examSubjectId,
        type: this.type ? this.type : undefined,
      })
        .then((res) => {
          if (res.data.status == "1") {
            this.startTime();
          } else if (res.data.status == "2") {
            window.open(res.data.result);
          }
        })
        .catch(() => {
          if (this.dcStatus == "1") {
            this.dcStatus = "0";
          }
        });
      // this.download(
      //   "/system/score/manage/export",
      //   {
      //     examId: this.xmxx.id,
      //     examSubjectId: this.queryParams.examSubjectId,
      //   },
      //   `成绩_${examSubjectName}_${new Date().getTime()}.xlsx`,
      //   { headers: { "Content-Type": "application/json;charset=UTF-8" } }
      // );
    },
    edit(row) {
      if (row) {
        this.editForm.row = row;
      }

      let checkObj = {};
      this.questionList.map((item) => {
        if (checkObj[item.questionTypeId]) {
          checkObj[item.questionTypeId].item.push(item);
        } else {
          checkObj[item.questionTypeId] = { item: [item], value: [] };
        }
      });

      let checkData = [];
      let checkRows = [];
      for (let key in checkObj) {
        checkData.push(checkObj[key]);
        checkRows.push({ indeterminate: false, value: false });
      }
      this.checkData = checkData;
      this.checkRows = checkRows;
      this.editKmVisible = true;
    },
    handleCheckAllChange(value) {
      let checkData = JSON.parse(JSON.stringify(this.checkData));
      checkData.map((item) => {
        if (value) {
          item.value = item.item.map((v) => {
            return v.questionId;
          });
        } else {
          item.value = [];
        }
      });
      this.checkData = checkData;

      this.handleCheckChange();
    },
    handleCheckRowChange(value, index) {
      let checkData = JSON.parse(JSON.stringify(this.checkData));
      if (value) {
        checkData[index].value = checkData[index].item.map((v) => {
          return v.questionId;
        });
      } else {
        checkData[index].value = [];
      }
      this.checkData = checkData;
      this.handleCheckChange();
    },
    handleCheckChange() {
      let isEmpty = !this.checkData.some((item) => {
        return item.value.length != 0;
      });
      let isSelAll = !this.checkData.some((item) => {
        return item.value.length != item.item.length;
      });
      let checkRows = [];
      this.checkData.map((item) => {
        let value = false;
        let indeterminate = false;
        let len = item.item.length;
        if (item.value.length == len) {
          value = true;
        } else if (item.value.length != 0) {
          indeterminate = true;
        }
        checkRows.push({ value, indeterminate });
      });

      this.checkRows = checkRows;
      this.checkAll = isSelAll;
      this.allIndeterminate = !isEmpty && !isSelAll;
    },
    editSubmit(keepOn) {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let zgt = [];
          let zgtzt = [];
          let kgt = [];

          this.checkData.map((item) => {
            item.value.map((v) => {
              let question = item.item.filter((f) => {
                return f.questionId == v;
              })[0];
              if (question.subjectiveType == 0) {
                kgt.push(v);
              } else if (question.groupQuestion == 1) {
                zgtzt.push(v);
              } else if (question.groupQuestion == 0) {
                zgt.push(v);
              }
            });
          });

          let examScoreBasicQuestionInputs = [];
          if (zgt.length > 0) {
            examScoreBasicQuestionInputs.push({
              questionIds: zgt,
              subjectiveType: 1,
              groupQuestion: 0,
            });
          }
          if (zgtzt.length > 0) {
            examScoreBasicQuestionInputs.push({
              questionIds: zgtzt,
              subjectiveType: 1,
              groupQuestion: 1,
            });
          }
          if (kgt.length > 0) {
            examScoreBasicQuestionInputs.push({
              questionIds: kgt,
              subjectiveType: 0,
              groupQuestion: null,
            });
          }

          if (examScoreBasicQuestionInputs.length == 0) {
            this.$modal.alert("请选择要修改的题目");
            return;
          }

          let operation = {
            "*": "multiply",
            "+": "add",
            "-": "subtract",
          };

          let data = {
            examId: this.xmxx.id,
            examSubjectId: this.queryParams.examSubjectId,
            examScoreBasicQuestionInputs,
            score: this.editForm.score.substring(1, this.editForm.score.length),
            operation: operation[this.editForm.score.substring(0, 1)],
            roundOff: this.editForm.roundOff,
          };

          if (this.editForm.row) {
            data.examStudentIds = [this.editForm.row.studentId];
          } else if (this.editType == "1") {
            data.admissionNos = this.editForm.admissionNos.split(",");
          } else if (this.editRange == "1") {
            data.schoolIds = this.editForm.schoolId;
          } else if (this.editRange == "2") {
            data.classIds = this.editForm.classId;
          }

          this.loading = true;
          systemScoreManageAdjustmentScore(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              if (keepOn) {
                this.handleCheckAllChange(false);
                this.editForm.score = "";
                this.editForm.roundOff = "1";
                this.editForm.admissionNos = "";
                this.editForm.schoolId = [];
                this.editForm.classId = [];

                this.$nextTick(() => {
                  this.$refs["editForm"].clearValidate();
                });
              } else {
                this.handleClose();
              }
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    blfsShow() {
      let blfsForm = JSON.parse(JSON.stringify(this.blfsForm));
      blfsForm.questionList = JSON.parse(JSON.stringify(this.questionList)).map(
        (item) => {
          return {
            ...item,
            score: "",
          };
        }
      );
      this.blfsForm = blfsForm;
      this.blfsVisible = true;
    },

    blfsSubmit() {
      this.$refs.blfsForm.validate((valid) => {
        if (valid) {
          let data = {
            examId: this.xmxx.id,
            examSubjectId: this.queryParams.examSubjectId,
            schoolId: this.blfsForm.schoolId,
            schoolName: this.xxlb.filter((item) => {
              return item.id == this.blfsForm.schoolId;
            })[0].schoolName,
            admissionNo: this.blfsForm.admissionNo,
            studentName: this.blfsForm.studentName,
            studentNo: this.blfsForm.studentNo,
            classId: this.blfsForm.classId,
            className: this.bjlb.filter((item) => {
              return item.id == this.blfsForm.classId;
            })[0].className,
          };

          data.examQuestionInputs = this.blfsForm.questionList.map((item) => {
            return {
              ...item,
              score: item.score ? item.score : "0",
            };
          });
          systemScoreManageAdditionScore(data).then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.handleClose();
            this.getList();
          });
        }
      });
    },
    closeImgViewer() {
      this.imgViewerVisible = false;
      const m = (e) => {
        e.preventDefault();
      };
      document.body.style.overflow = "auto";
      document.removeEventListener("touchmove", m, true);
    },
    dtk(row) {
      this.imgList = [row.frontImgPath, row.backImgPath];
      this.imgViewerVisible = true;
      const m = (e) => {
        e.preventDefault();
      };
      document.body.style.overflow = "hidden";
      document.addEventListener("touchmove", m, false); // 禁止页面滑动
    },
    cjfx() {
      if (process.env.NODE_ENV === "production") {
        window.open("https://ea.bsedu.com/html/login");
      } else {
        window.open("https://test-ea.bsedu.com/html/login");
      }
    },
    yyd() {
      if (process.env.NODE_ENV === "production") {
        window.open("https://ecp.bsedu.com/#/login");
      } else {
        window.open("https://test-ecp.bsedu.com/#/login");
      }
    },

    xgfs(row) {
      this.$router.push({
        path: "/cjgl/xgfs/index",
        query: {
          admissionNo: row.admissionNo,
          examSubjectId: this.queryParams.examSubjectId,
          examId: this.xmxx.id,
        },
      });
    },
    showXgfs(row) {
      return row.examScoreManageQuestionVos.some((item) => {
        return item.ratingSwitch == 1;
      });
    },
  },
  deactivated() {
    if (this.timer) {
      this.endTime();
    }
  },
  beforeDestroy() {
    if (this.timer) {
      this.endTime();
    }
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-cascader,
  .el-select {
    width: 240px;
  }

  .edit-info {
    display: flex;

    p {
      margin: 0;
      margin-right: 20px;

      span {
        font-weight: bold;
      }
    }
  }
}

.disciplinary {
  text-decoration: line-through;
}

.check-row {
  margin: 15px 0;
}

.el-dropdown {
  padding: 8px 15px;
  font-size: 14px;
  border-radius: 3px;
  background: #1a48db;
  color: #fff;
  margin-right: 10px;
  cursor: pointer;
}
</style>
